#!/bin/bash

# MD5文件校验脚本
# 用法: ./md5_checker.sh [MD5文件] [校验目录]

# 设置默认值
MD5_FILE="${1:-md5sums.txt}"
CHECK_DIR="${2:-.}"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # 无颜色

# 打印颜色输出函数
print_status() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 检查MD5文件是否存在
if [ ! -f "$MD5_FILE" ]; then
    print_status "$RED" "错误: MD5文件 '$MD5_FILE' 不存在"
    echo "请先使用以下命令生成MD5文件:"
    echo "  find \"$CHECK_DIR\" -type f -exec md5sum {} \; > \"$MD5_FILE\""
    exit 1
fi

# 检查目标目录是否存在
if [ ! -d "$CHECK_DIR" ]; then
    print_status "$RED" "错误: 目录 '$CHECK_DIR' 不存在"
    exit 1
fi

echo "开始MD5校验..."
echo "MD5文件: $MD5_FILE"
echo "校验目录: $CHECK_DIR"
echo "----------------------------------------"

# 统计变量
total_files=0
passed_files=0
failed_files=0
missing_files=0

# 逐行读取MD5文件并进行校验
while IFS= read -r line; do
    # 跳过空行和注释行
    if [[ -z "$line" || "$line" =~ ^# ]]; then
        continue
    fi
    
    # 提取MD5值和文件名
    expected_md5=$(echo "$line" | awk '{print $1}')
    filename=$(echo "$line" | cut -d' ' -f3-)
    
    # 如果文件名是相对路径，转换为绝对路径
    if [[ "$filename" != /* ]]; then
        filename="$CHECK_DIR/$filename"
    fi
    
    ((total_files++))
    
    # 检查文件是否存在
    if [ ! -f "$filename" ]; then
        print_status "$RED" "❌ 文件不存在: $filename"
        ((missing_files++))
        continue
    fi
    
    # 计算当前文件的MD5值
    current_md5=$(md5sum "$filename" 2>/dev/null | awk '{print $1}')
    
    if [ -z "$current_md5" ]; then
        print_status "$RED" "❌ 计算MD5失败: $filename"
        ((failed_files++))
        continue
    fi
    
    # 比较MD5值
    if [ "$current_md5" = "$expected_md5" ]; then
        print_status "$GREEN" "✅ 通过: $filename"
        ((passed_files++))
    else
        print_status "$RED" "❌ 失败: $filename"
        echo "   期望: $expected_md5"
        echo "   实际: $current_md5"
        ((failed_files++))
    fi
done < "$MD5_FILE"

echo "----------------------------------------"
echo "校验完成!"

# 打印统计结果
if [ $failed_files -eq 0 ] && [ $missing_files -eq 0 ]; then
    print_status "$GREEN" "🎉 所有文件校验通过! ($passed_files/$total_files)"
    exit 0
else
    print_status "$YELLOW" "📊 统计结果:"
    echo "   总文件数: $total_files"
    echo "   通过: $passed_files"
    echo "   失败: $failed_files"
    echo "   缺失: $missing_files"
    
    if [ $failed_files -gt 0 ] || [ $missing_files -gt 0 ]; then
        print_status "$RED" "❌ 校验未通过!"
        exit 1
    else
        print_status "$GREEN" "✅ 校验通过!"
        exit 0
    fi
fi
